﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace StationUpdate.Util
{
    public class WebDown
    {
        ///
        /// 下载文件方法
        ///
        /// 文件保存路径和文件名
        /// 返回服务器文件名
        ///
        public static bool DeownloadFile(string sourceFile, string desFile)
        {
            bool flag = false;
            long SPosition = 0;
            FileStream FStream = null;
            Stream myStream = null;

            string desDir= desFile.Substring(0,desFile.LastIndexOf(@"\") + 1);

            if (!Directory.Exists(desDir))
            {
                DirectoryInfo d = new DirectoryInfo(desFile);
                d.Create();
            }

            string fileName = sourceFile.Substring(sourceFile.LastIndexOf(@"/") + 1);
           

            try
            {
                //判断要下载的文件夹是否存在
                if (File.Exists(desFile))
                {
                    FileInfo fineInfo = new FileInfo(desFile);
                    long serverFileLength = GetHttpLength(sourceFile);
                    if (fineInfo.Length == serverFileLength && serverFileLength > 0)
                    {//文件是完整的，直接结束下载任务
                        return true;
                    }
                    //打开上次下载的文件
                    FStream = File.OpenWrite(desFile);
                    //获取已经下载的长度
                    SPosition = FStream.Length;
                    FStream.Seek(SPosition, SeekOrigin.Current);
                }
                else
                {
                    //文件不保存创建一个文件
                    FStream = new FileStream(desFile, FileMode.Create);
                    SPosition = 0;
                }

                //打开网络连接
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(sourceFile);
                if (SPosition > 0)
                {
                    myRequest.AddRange(SPosition);             //设置Range值
                }
                myRequest.Headers.Add("Authorization", AuthUtil.getAuth());

                //向服务器请求,获得服务器的回应数据流
                myStream = myRequest.GetResponse().GetResponseStream();
                //定义一个字节数据
                byte[] btContent = new byte[512];
                int intSize = 0;
                intSize = myStream.Read(btContent, 0, 512);
                while (intSize > 0)
                {
                    FStream.Write(btContent, 0, intSize);
                    intSize = myStream.Read(btContent, 0, 512);
                }
                flag = true;        //返回true下载成功
            }
            catch (Exception ex)
            {
                SysLog.WriteTxtLog("下载文件时异常：" + ex.Message);
            }
            finally
            {
                //关闭流
                if (myStream != null)
                {
                    myStream.Close();
                    myStream.Dispose();
                }
                if (FStream != null)
                {
                    FStream.Close();
                    FStream.Dispose();
                }
            }
            return flag;
        }

        static long GetHttpLength(string url)
        {
            long length = 0;
            try
            {
                var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "HEAD";
                req.Timeout = 5000;
                req.Headers.Add("Authorization", AuthUtil.getAuth());
                var res = (HttpWebResponse)req.GetResponse();
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    length = res.ContentLength;
                }
                res.Close();
                return length;
            }
            catch (WebException wex)
            {
                return 0;
            }
        }

    }
}
